package com.aitaoxue.palx.ui;

import io.rong.imkit.RongIM;
import io.rong.imlib.RongIMClient.ConnectCallback;
import io.rong.imlib.RongIMClient.ErrorCode;

import java.util.Set;
import java.util.regex.Pattern;

import org.apache.http.Header;
import org.apache.http.client.CookieStore;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.cookie.Cookie;
import org.apache.http.protocol.HttpContext;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import butterknife.InjectView;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

import com.aitaoxue.palx.AppContext;
import com.aitaoxue.palx.AppManager;
import com.aitaoxue.palx.R;
import com.aitaoxue.palx.RongCloudEvent;
import com.aitaoxue.palx.api.ApiHttpClient;
import com.aitaoxue.palx.api.remote.AitaoXueApi;
import com.aitaoxue.palx.base.BaseActivity;
import com.aitaoxue.palx.bean.Base;
import com.aitaoxue.palx.ui.register.ForgetPasswordActivity;
import com.aitaoxue.palx.ui.register.RegisterActivity;
import com.aitaoxue.palx.util.GsonUtil;
import com.aitaoxue.palx.util.MD5Utils;
import com.aitaoxue.palx.util.StringUtils;
import com.aitaoxue.palx.util.TDevice;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;

public class LoginActivity extends BaseActivity implements Callback {

	// private static final String TEST_TOKEN =
	// "boBTsa2EiWqj/r0hqsbfl1f68qAWFx6ILQcQDDNQxptNXOPzQMkwSbAMTq6ou78IL649ByNEjddJFl+XfNgkQi0zUcjlW6qt";

	private long exitTime=0;
	
	private static final int LOGIN_SUCCESS = 200;

	@InjectView(R.id.username)
	EditText etUsername;

	@InjectView(R.id.password)
	EditText etPassword;

	@InjectView(R.id.post)
	Button post;

	@InjectView(R.id.register)
	TextView register;

	@InjectView(R.id.forget_password)
	TextView forgetPassword;

	private String username = null;
	private String password = null;

	private Handler handler;

	private boolean isRobot = false;

	Pattern pattern = Pattern.compile("^\\d{11}$");

	@Override
	protected int getLayoutId() {
		return R.layout.login;
	}

	@Override
	protected boolean hasBackButton() {
		return true;
	}

	@Override
	protected int getActionBarCustomView() {
		return R.layout.login_title;
	}

	@Override
	protected int getActionBarTitle() {
		return R.string.login;
	}

	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.post:
			if (checkValid()) {
				if (TDevice.hasInternet()) {
					showWaitDialog(R.string.logining);
					if (isRobot) {
						AitaoXueApi.login(username, password, mHandler);
					} else {
						AitaoXueApi.login(username, MD5Utils.md5(password),
								mHandler);
					}
					// String md5Password = MD5Utils.md5(password);
				} else {
					showToast(R.string.no_internet, 0, 0);
				}
			}
			break;
		case R.id.register:
			Intent intent = new Intent(this, RegisterActivity.class);
			startActivity(intent);
			break;
		case R.id.forget_password:
			Intent intent2 = new Intent(this, ForgetPasswordActivity.class);
			startActivity(intent2);
			break;
		default:
			break;
		}
	}

	@Override
	public void initView() {
		post.setOnClickListener(this);
		register.setOnClickListener(this);
		forgetPassword.setOnClickListener(this);
		handler = new Handler(this);
		
		AppManager.getAppManager().addActivity(this);
	}

	@Override
	public void initData() {
	}

	@Override
	protected void onResume() {
		super.onResume();

		username = AppContext.getInstance().getProperty("user.username");
		password = AppContext.getInstance().getProperty("user.password");
		if (username != null || password != null) {
			etUsername.setText(username);
			etPassword.setText(password);
		}

		// 自动登录
		if (username != null || password != null) {
			handler.postDelayed(new Runnable() {

				@Override
				public void run() {
					isRobot = true;
					onClick(post);
				}
			}, 100);
		}
	}

	private boolean checkValid() {
		username = etUsername.getText().toString();
		password = etPassword.getText().toString();
		if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
			showToast(R.string.empty_input, 0, Gravity.CENTER_VERTICAL);
			return false;
		} else if (!pattern.matcher(username).matches()) {
			showToast(R.string.error_phone, 0, Gravity.CENTER_VERTICAL);
			return false;
		}

		return true;
	}

	private AsyncHttpResponseHandler mHandler = new AsyncHttpResponseHandler() {

		@Override
		public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
			// hideWaitDialog();
			String result = new String(arg2);
			Base base = GsonUtil.GsonToBean(result, Base.class);
			switch (Integer.parseInt(base.getStatus())) {
			case 0: // 成功
				setCookies();
				// 保存个人信息
				// TODO
				// 获取token,连接融云
				getToken();

				// gotoMainActivity();
				break;
			case 11: // 手机号未注册
				showToast("手机号未注册", 0, 0);
				break;
			case 2: // 身份错误
				showToast("此号码已在家长端注册", 0, 0);
				break;
			default:
				break;
			}
		}

		@Override
		public void onFailure(int arg0, Header[] arg1, byte[] arg2,
				Throwable arg3) {
			System.out.println("aaa");
		}
	};

	private void setCookies() {
		AsyncHttpClient client = ApiHttpClient.getHttpClient();
		HttpContext httpContext = client.getHttpContext();
		CookieStore cookies = (CookieStore) httpContext
				.getAttribute(ClientContext.COOKIE_STORE);
		if (cookies != null) {
			String tmpcookies = "";
			for (Cookie c : cookies.getCookies()) {
				tmpcookies += (c.getName() + "=" + c.getValue()) + ";";
			}
			ApiHttpClient.setCookie(tmpcookies);
		}
	}

	private void gotoMainActivity() {
		String setAlias = AppContext.getInstance().getProperty("setalias");
		if (setAlias == null || setAlias.equals("no")) {
			JPushInterface.setAlias(AppContext.getInstance(), AppContext
					.getInstance().getProperty("user.username"),
					new TagAliasCallback() {

						@Override
						public void gotResult(int arg0, String arg1,
								Set<String> arg2) {
							// 这里有很小的概率失败
							hideWaitDialog();
							AppContext.getInstance().setProperty("setalias",
									"yes");
							Intent intent = new Intent(LoginActivity.this,
									MainActivity.class);
							startActivity(intent);
							//这里不知道有没有错
							finish();
						}
					});
		} else {
			Intent intent = new Intent(LoginActivity.this, MainActivity.class);
			startActivity(intent);
			finish();
		}
	}

	@Override
	public boolean handleMessage(Message msg) {
		switch (msg.what) {
		case LOGIN_SUCCESS:
			// hideWaitDialog();
			// 保存用户名和密码
			if (!isRobot) {
				AppContext.getInstance().setProperty("user.username", username);

				AppContext.getInstance().setProperty("user.password",
						MD5Utils.md5(password));
			}

			gotoMainActivity();
			break;

		default:
			break;
		}

		return false;
	}

	private void getToken() {
		String token = AppContext.getInstance().getProperty("user.token");
		if (token == null) {
			// 重新获取token
			// TODO
			// getTokenSuccess(TEST_TOKEN);
			getNewToken();
		} else {
			getTokenSuccess(token);
		}
	}

	private void getTokenSuccess(String token) {
		if ("com.aitaoxue.palx".equals(AppContext
				.getCurProcessName(getApplicationContext()))) {
			RongIM.connect(token, new ConnectCallback() {

				@Override
				public void onSuccess(String arg0) {
					RongCloudEvent.getInstance().setOtherListener();

					handler.obtainMessage(LOGIN_SUCCESS).sendToTarget();
				}

				@Override
				public void onError(ErrorCode arg0) {
					// TODO Auto-generated method stub

				}

				@Override
				public void onTokenIncorrect() {
				}
			});
		}
	}

	private void getNewToken() {
		AitaoXueApi.createIMToken(tokenHandler);
	}

	private AsyncHttpResponseHandler tokenHandler = new AsyncHttpResponseHandler() {

		@Override
		public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
			String res = new String(arg2);

			try {
				JSONObject json = new JSONObject(res);
				JSONArray array = json.getJSONArray("content");
				JSONObject jsonObject = array.getJSONObject(0);
				String token = jsonObject.getString("token");

				AppContext.getInstance().setProperty("user.token", token);
				getTokenSuccess(token);
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}

		@Override
		public void onFailure(int arg0, Header[] arg1, byte[] arg2,
				Throwable arg3) {
			// TODO Auto-generated method stub

		}
	};
	
	public void onBackPressed() {
		if((System.currentTimeMillis()-exitTime)>2000){
			showToast("再按一次退出程序", 0, 0);
			exitTime=System.currentTimeMillis();
		}else{
			AppManager.getAppManager().finishAllActivity();
		}
	}
}












